<template>
  <div class="tab-container">
    <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" :inline="true" label-width="68px">
      <px-form-item label="时间" style="width: 460px">
        <px-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="monthrange"
          range-separator="-"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          :clearable="false"
          @change="handleMonthChange"
        />
      </px-form-item>
      <px-form-item>
        <px-button type="primary" @click="getList">查询</px-button>
        <px-button @click="resetQuery">重置</px-button>
      </px-form-item>
    </px-form>

    <div class="btn-con">
      <px-button v-has="'ALL_ENERGY_ENERGYREPORT_OVERVIEW_EXPORT_BTN'" type="primary" plain class="btn-item" @click="handleExport">导出</px-button>
    </div>

    <px-table
      v-loading="loading"
      :data="tableData"
      :header-cell-style="{ background: '#e7eefb', color: '#000' }"
      height="calc(100vh - 258px)"
      border
      show-overflow-tooltip
      :cell-class-name="cellClassName"
    >
      <px-table-column type="index" label="序号" width="60" align="center" fixed />

      <!-- 固定列 - 不可编辑 -->
      <px-table-column prop="monitorObject" label="监测对象" min-width="120" align="center" fixed />
      <px-table-column prop="monitorItem" label="监测项目" min-width="120" align="center" fixed />
      <px-table-column prop="unit" label="单位" min-width="100" fixed align="center" />
      <px-table-column prop="department" label="责任部门" min-width="120" align="center" fixed />

      <!-- 动态日期列 -->
      <px-table-column v-for="(date, index) in dateColumns" :key="index" :prop="date" :label="date" width="200">
        <template #default="{ row, column }">
          <div class="cell-content">
            <template v-if="row[column.property].isEditing">
              <px-input-number
                v-model="row[column.property].editingValue"
                :min="0"
                :max="1000000"
                :precision="2"
                :step="0.01"
                placeholder="输入大于等于0的数字"
                class="edit-input"
                size="small"
              />
              <div class="edit-buttons">
                <px-tooltip content="保存" placement="top">
                  <px-button v-has="'ALL_ENERGY_ENERGYREPORT_OVERVIEW_EDIT'" link type="success" @click="handleSave(row, column.property)"
                    ><SaveIcon
                  /></px-button>
                </px-tooltip>
                <px-tooltip content="取消" placement="top">
                  <px-button
                    v-has="'ALL_ENERGY_ENERGYREPORT_OVERVIEW_EDIT'"
                    style="margin: 0"
                    link
                    type="danger"
                    @click="handleCancel(row, column.property)"
                  >
                    <CancelIcon />
                  </px-button>
                </px-tooltip>
              </div>
            </template>

            <template v-else>
              <div class="cell-content" @click.stop="handleEdit(row, column.property)">
                <span class="cell-value">{{ row[column.property]?.value || "-" }}</span>
                <div v-if="row[column.property].isSubmit">
                  <px-tooltip content="提交" placement="top">
                    <px-button v-has="'ALL_ENERGY_ENERGYREPORT_OVERVIEW_EDIT'" link type="success" @click.stop="handleSubmit(row, column.property)"
                      ><SubmitIcon
                    /></px-button>
                  </px-tooltip>
                </div>
              </div>
            </template>
          </div>
        </template>
      </px-table-column>

      <!-- 合计列 -->
      <px-table-column prop="total" label="合计" width="200">
        <template #default="{ row, column }">
          <div class="cell-content">
            <template v-if="row[column.property].isEditing">
              <px-input-number
                v-model="row[column.property].editingValue"
                :min="0"
                :max="1000000"
                :precision="2"
                :step="0.01"
                placeholder="输入大于等于0的数字"
                class="edit-input"
              />
              <div class="edit-buttons">
                <px-tooltip content="保存" placement="top">
                  <px-button v-has="'ALL_ENERGY_ENERGYREPORT_OVERVIEW_EDIT'" link type="success" @click="handleSave(row, column.property)"
                    ><SaveIcon
                  /></px-button>
                </px-tooltip>
                <px-tooltip content="取消" placement="top">
                  <px-button
                    v-has="'ALL_ENERGY_ENERGYREPORT_OVERVIEW_EDIT'"
                    style="margin: 0"
                    link
                    type="danger"
                    @click="handleCancel(row, column.property)"
                  >
                    <CancelIcon />
                  </px-button>
                </px-tooltip>
              </div>
            </template>

            <template v-else>
              <div class="cell-content" @click.stop="handleEdit(row, column.property)">
                <span class="cell-value">{{ row[column.property]?.value || "-" }}</span>
                <div v-if="row[column.property].isSubmit">
                  <px-tooltip content="提交" placement="top">
                    <px-button v-has="'ALL_ENERGY_ENERGYREPORT_OVERVIEW_EDIT'" link type="success" @click.stop="handleSubmit(row, column.property)"
                      ><SubmitIcon
                    /></px-button>
                  </px-tooltip>
                </div>
              </div>
            </template>
          </div>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="100" />
      </template>
    </px-table>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_ENERGY_ENERGYREPORT_OVERVIEW"
});
import { getData, updateData } from "@/api/energy/energyOverview";
import dayjs from "dayjs";
import type { TableColumnCtx } from "element-plus/es/components/table/src/table-column/defaults";
import { PxMessage } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from "vue";
import SaveIcon from "@/assets/svg/energy/save.svg?component";
import CancelIcon from "@/assets/svg/energy/cancel.svg?component";
import SubmitIcon from "@/assets/svg/energy/submit.svg?component";

const { proxy }: any = getCurrentInstance();

interface CellData {
  value: string | null;
  code: string | null;
  bizTime: string | null;
  mark: string | null;
  editable: boolean;
  isEditing: boolean;
  isSubmit: boolean | null;
  editingValue: string | null;
  isGreen: boolean | null;
  copyIsGreen: boolean | null;
}

interface TableDataItem {
  monitorObject: string;
  monitorItem: string;
  unit: string;
  department: string;
  total: CellData;
  [key: string]: CellData | any;
}

const loading = ref(true);

const data = reactive<Record<string, any>>({
  queryParams: {},
  resData: {}
});

const { queryParams, resData } = toRefs(data);

// 响应式数据
const dateRange = ref<any>([]);
const tableData = ref<TableDataItem[]>([]);
const dateColumns = ref<string[]>([]);

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d: any = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

// 设置默认查询时间为近一年
const defaultQueryDate = () => {
  const date = new Date();
  date.setMonth(date.getMonth() - 11); // 近一年
  return [`${proxy.parseTime(date, "{y}-{m}")}-01`, getCurrentMonthL()];
};

const handleMonthChange = val => {
  if (!val) return;
  const [start, end] = val;
  dateRange.value = [dayjs(start).startOf("month").format("YYYY-MM-DD"), dayjs(end).endOf("month").format("YYYY-MM-DD")];
};

// 日期选择器选项
const pickerOptions = {
  disabledDate(time: Date) {
    return time.getTime() > Date.now();
  }
};
// 列表
const getList = async () => {
  loading.value = true;
  try {
    const res: any = await getData(proxy.addDateRange(queryParams.value, dateRange.value, "startDate", "endDate"));
    processApiData(res);
    resData.value = res;
    loading.value = false;
  } catch (error) {
    PxMessage.error("数据获取失败");
    loading.value = false;
    console.error(error);
  }
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = defaultQueryDate();
  proxy.resetForm("queryRef");
  getList();
};

// 处理API返回数据
const processApiData = response => {
  const { body, header } = response;

  // 提取日期列（跳过前4个固定列）
  dateColumns.value = header.slice(4, -1); // 排除最后的合计列

  // 处理表格数据
  tableData.value = body.map(item => {
    const rowData: TableDataItem = {
      monitorObject: item.ahead[0],
      monitorItem: item.ahead[1],
      unit: item.ahead[2],
      department: item.ahead[3],
      total: {
        value: null,
        code: null,
        bizTime: null,
        mark: null,
        editable: false,
        isEditing: false,
        isSubmit: false,
        editingValue: null
      }
    };

    // 填充日期列数据
    item.content.forEach(contentItem => {
      if (contentItem.bizTime) {
        const monthKey = contentItem.bizTime.slice(0, 7); // 取年月部分
        rowData[monthKey] = {
          value: contentItem.value,
          code: contentItem.code,
          bizTime: contentItem.bizTime,
          mark: contentItem.mark,
          editable: contentItem.mark !== "lock", // 根据mark判断是否可编辑
          isEditing: false,
          isSubmit: false,
          editingValue: null,
          isGreen: contentItem.mark === "green",
          copyIsGreen: contentItem.mark === "green"
        };
      } else if (contentItem.value) {
        // 合计数据
        rowData.total = {
          value: contentItem.value,
          code: contentItem.code,
          bizTime: contentItem.bizTime,
          mark: contentItem.mark,
          editable: contentItem.mark !== "lock", // 根据mark判断是否可编辑
          isEditing: false,
          isSubmit: false,
          editingValue: null,
          isGreen: contentItem.mark === "green",
          copyIsGreen: contentItem.mark === "green"
        };
      }
    });

    return rowData;
  });
};

// 单元格点击编辑
const handleEdit = (row: TableDataItem, column: string) => {
  const cellData = column === "total" ? row.total : (row[column] as CellData);
  if (!cellData.editable) {
    return;
  }
  cellData.editingValue = cellData.value || "";
  cellData.isEditing = true;
  cellData.copyIsGreen = cellData.isGreen;
  cellData.isGreen = false;
};

// 保存
const handleSave = async (row: TableDataItem, column: string) => {
  const cellData = column === "total" ? row.total : (row[column] as CellData);
  if (!cellData.editingValue && cellData.editingValue !== "0") {
    PxMessage.warning("请输入有效值");
    return;
  }
  cellData.isEditing = false;
  cellData.isSubmit = true;
  cellData.value = cellData.editingValue;
};

// 提交
const handleSubmit = async (row: TableDataItem, column: string) => {
  const cellData = column === "total" ? row.total : (row[column] as CellData);
  try {
    await updateData({
      code: cellData.code,
      bizTime: cellData.bizTime,
      value: cellData.value,
      mark: "green", // 提交后标记为green
      editable: true
    });
    // // 更新单元格值
    // const updatedCell: CellData = {
    //   value: row.editingValue,
    //   code: cellData.code,
    //   bizTime: cellData.bizTime,
    //   mark: "green",
    //   editable: true
    // };
    // row[column] = updatedCell;
    // await getList();
    // 退出编辑状态
    cellData.isSubmit = false;
    cellData.isGreen = true;
    // cellData.editingValue = null;
    PxMessage.success("提交成功");
  } catch (error) {
    PxMessage.error("提交失败");
    console.error(error);
  }
};

// 取消编辑
const handleCancel = (row: TableDataItem, column: string) => {
  const cellData = column === "total" ? row.total : (row[column] as CellData);
  cellData.isEditing = false;
  cellData.isGreen = cellData.copyIsGreen;
};

// 单元格类名
const cellClassName = ({ row, column }: { row: TableDataItem; column: TableColumnCtx<TableDataItem> }) => {
  if (column.property && column.property !== "total") {
    const cellData = row[column.property] as CellData;

    if (cellData?.mark === "lock") {
      return "lock-cell";
    } else if (cellData.isGreen) {
      return "green-cell";
    } else {
      return "white-cell";
    }
  }
  return "";
};

/** 导出按钮操作 */
const handleExport = () => {
  const params = { ...resData.value, title: "能源一览表.xlsx" };
  proxy.download("post", "/energy/report/exportInventory", params, "能源一览表.xlsx");
};

// 初始化加载数据
onMounted(() => {
  // 初始化查询日期
  dateRange.value = defaultQueryDate();
  getList();
});
</script>

<style lang="scss" scoped>
.tab-container {
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 4px;
}

.custom-form-ui-new {
  margin-bottom: 0;
}

.btn-con {
  display: flex;
  align-items: center;
  justify-content: flex-start;

  .btn-item {
    margin-bottom: 16px;
  }
}

.table-header {
  display: flex;
  gap: 10px;
}

.cell-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;
}

.cell-value {
  flex: 1;
}

.edit-input {
  width: calc(100% - 44px);
  margin-right: 8px;

  :deep(.px-input-number__decrease),
  :deep(.px-input-number__increase) {
    display: none;
  }

  :deep(.px-input__wrapper) {
    padding: 0 12px;
  }
}

.edit-buttons {
  display: flex;
}

:deep(.green-cell) {
  background-color: rgb(144 238 144 / 30%) !important;
}

:deep(.white-cell) {
  background-color: #fff !important;
}

:deep(.lock-cell) {
  cursor: not-allowed;
  background-color: #fff !important;
}

:deep(.lock-cell .px-button) {
  display: none;
}
</style>
